package com.hyopt.common.utils;

import com.hyopt.common.exception.ServiceException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import java.io.*;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

public class FileUtils {
	public static Log log = LogFactory.getLog(FileUtils.class);

	public static boolean uploadFile(InputStream is, String filePath) {
		boolean retCode = false;
		byte[] buffer = new byte[1024];
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(filePath));

			int n = -1;
			while ((n = is.read(buffer, 0, buffer.length)) != -1) {
				fos.write(buffer, 0, n);
			}

			retCode = true;
//			System.out.println("upload file success...");
		} catch (FileNotFoundException fnfe) {
			System.out.println("fnfe:" + fnfe);
		} catch (IOException ioe) {
			System.out.println("ioe:" + ioe);
		} finally {
			if (fos != null) {
				try {
					fos.close();
					fos = null;
				} catch (IOException e) {
					log.error(e);
				}
			}
			if (is != null) {
				try {
					is.close();
					is = null;
				} catch (IOException e) {
					log.error(e);
				}

			}
		}
		return retCode;
	}

	public static boolean copyFile(String myfile, String filePath) {
		boolean retCode = false;
		byte[] buffer = new byte[10240];
		FileOutputStream fos = null;
		FileInputStream is = null;

		try {
			fos = new FileOutputStream(new File(filePath));
			is = new FileInputStream(new File(myfile));

			int n = -1;
			while ((n = is.read(buffer, 0, buffer.length)) != -1) {
				fos.write(buffer, 0, n);
			}
			retCode = true;
//			System.out.println("copy file success...");
		} catch (FileNotFoundException fnfe) {
			System.out.println("fnfe:" + fnfe);
		} catch (IOException ioe) {
			System.out.println("ioe:" + ioe);
		} finally {
			if (fos != null) {
				try {
					fos.close();
					fos = null;
				} catch (IOException e) {
					log.error(e);
				}
			}
			if (is != null) {
				try {
					is.close();
					is = null;
				} catch (IOException e) {
					log.error(e);
				}

			}
		}
		return retCode;
	}

	public static String getXmlContent(File xmlFile) {
		try {
			Document document = new SAXReader().read(xmlFile);
			return document.asXML();
		} catch (DocumentException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static String getFileContent(String fileName) {

		BufferedReader reader = null;
		StringBuilder fileContent = new StringBuilder();
		try {
			File f = new File(fileName);

			reader = new BufferedReader(new FileReader(f));
			String line = "";
			while ((line = reader.readLine()) != null) {
				fileContent.append(line);
				fileContent.append("\n");
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
					reader = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return fileContent.toString();
	}

	public static String getFileContent(InputStream is) {

		BufferedReader reader = null;
		StringBuilder fileContent = new StringBuilder();
		try {
			reader = new BufferedReader(new InputStreamReader(is));
			String line = "";
			while ((line = reader.readLine()) != null) {
				fileContent.append(line);
				fileContent.append("\n");
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
					reader = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return fileContent.toString();

	}

	public static boolean setFileContent(String path, String content) {
		boolean flag = false;
		DataOutputStream dos = null;
		try {
			if (content != null && content.length() >= 0) {
				byte[] abyte = content.getBytes();
				dos = new DataOutputStream(new FileOutputStream(path));
				dos.write(abyte, 0, abyte.length);
				dos.flush();

				flag = true;
			}
		} catch (FileNotFoundException e) {
			log.error("fnfe:" + e);
		} catch (IOException e) {
			log.error("ioe:" + e);
		} finally {
			if (dos != null) {
				try {
					dos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				dos = null;
			}
		}
		return flag;
	}

	public static String file2Base64String(String filePath, String tmpDir) {
		File file = new File(filePath);

		String tmpFilePath = tmpDir + "/" + UUID.randomUUID().toString() + ".base64";
		File tmpFile = new File(tmpFilePath);

		StringBuffer sb = new StringBuffer();
		BufferedReader br = null;
		try {
			Base64.encode(file, tmpFile);
			// Read All Base 64 File
			br = new BufferedReader(new FileReader(tmpFile));
			String tmpStr = null;
			while ((tmpStr = br.readLine()) != null) {
				sb.append(tmpStr);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
					br = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		tmpFile.delete();
		return sb.toString();

	}

	public static String getFileExt(String fileName) {
		if (fileName == null)
			return "";

		String ext = "";
		int lastIndex = fileName.lastIndexOf(".");
		if (lastIndex >= 0) {
			ext = fileName.substring(lastIndex + 1).toLowerCase();
		}

		return ext;
	}

	public static String renameFile(String name, String id, String suff) {
		String ext = "";
		if (!suff.startsWith(".")) {
			ext = "." + suff;
		} else {
			ext = suff;
		}
		return MD5Util.MD5(name + id + System.currentTimeMillis()) + ext;
	}

	/**
	 * 获取文件的编码
	 *
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static String getCharset(String fileName) throws IOException {
		BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
		int p = (bin.read() << 8) + bin.read();
		String code = null;
		switch (p) {
		case 0xefbb:
			code = "UTF-8";
			break;
		case 0xfffe:
			code = "Unicode";
			break;
		case 0xfeff:
			code = "UTF-16BE";
			break;
		default:
			code = "GBK";
		}
		bin.reset();
		return code;
	}

	public static InputStreamReader getInputStreamReader(InputStream inputStream, String defaultEnc)
			throws IOException {
		int BOM_SIZE = 4;
		PushbackInputStream internalIn = new PushbackInputStream(inputStream, BOM_SIZE);
		byte[] bom = new byte[4];
		String encoding;
		int n, unread;
		n = internalIn.read(bom, 0, bom.length);
		if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00) && (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF)) {
			encoding = "UTF-32BE";
			unread = n - 4;
		} else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE) && (bom[2] == (byte) 0x00)
				&& (bom[3] == (byte) 0x00)) {
			encoding = "UTF-32LE";
			unread = n - 4;
		} else if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB) && (bom[2] == (byte) 0xBF)) {
			encoding = "UTF-8";
			unread = n - 3;
		} else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) {
			encoding = "UTF-16BE";
			unread = n - 2;
		} else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) {
			encoding = "UTF-16LE";
			unread = n - 2;
		} else {
			// Unicode BOM mark not found, unread all bytes
			encoding = defaultEnc;
			unread = n;
		}
		if (unread > 0)
			internalIn.unread(bom, (n - unread), unread);

		if (encoding == null) {
			return new InputStreamReader(internalIn);
		} else {
			return new InputStreamReader(internalIn, encoding);
		}
	}

	/**
	 * 图片单独上传
	 * 
	 * @param request
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public static String springUpload(HttpServletRequest request) throws Exception {
		String path = System.getProperty(Constant.SYS_PUT);
		String fileName = null;
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile(iter.next());
//				System.out.println(file.getName());
//				System.out.println(file.getOriginalFilename());
				if (file != null) {
					fileName = UUID.randomUUID().toString() + file.getOriginalFilename().substring(
							file.getOriginalFilename().lastIndexOf("."));
					path = path + fileName;
					// 文件开始上传
					file.transferTo(new File(path));
				}
			}
		}
		return fileName;
	}

	/**
	 * 大文件上传
	 * @param request
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public static String testUpload(HttpServletRequest request) throws Exception {
		String path = System.getProperty(Constant.Path.ALARM) + "/" + "小米枪战.apk";
		String fileName = null;
		request.getAttributeNames();
		String fileNames = ((MultipartFile) request).getOriginalFilename();   //原文件名
//		System.out.println(fileNames);
		InputStream in = request.getInputStream();
		File uploadFile = new File(path);
		if(!uploadFile.getParentFile().exists()){
			uploadFile.getParentFile().mkdirs();
		}
		FileOutputStream fos = new FileOutputStream(uploadFile);
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		int b = 1;
		byte[] buffer = new byte [ 1024 ];
		while ((b = in.read(buffer)) != -1) {
			bos.write(buffer,0,b);
		}
		bos.flush();
		bos.close();
		fos.close();
		in.close();
		return fileName;

	}

	
	/**
	 * 
	 * @param request	上传的文件流
	 * @param path	上传的路径
	 * @return
	 * @throws Exception
	 */
	public static String springUpload(HttpServletRequest request,String path) throws Exception {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multiRequest.getFileNames();
			String name = null;
			while (iter.hasNext()) {
				if (!(new File(path)).exists() ){
					new File(path).mkdirs();
				}
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					name = UUID.randomUUID().toString() + file.getOriginalFilename().substring(
							file.getOriginalFilename().lastIndexOf("."));
					path = path + name;
					if (new File(path).exists()){
						throw new ServiceException("文件已存在");
					}
					// 文件开始上传
					file.transferTo(new File(path));
				}
			}
			return name;
		}else{
			return null;
		}
	}
	

	
	public String multiUpload(@RequestParam("idPic") MultipartFile[] multipartfiles)   
            throws IllegalStateException, IOException {  
        //保存文件的目录  
        String savePath = "";//request.getSession().getServletContext().getRealPath("/") + "/uploadTempDirectory/";  
        if(null != multipartfiles && multipartfiles.length > 0){  
            //遍历并保存文件  
            for(MultipartFile file : multipartfiles){  
                file.transferTo(new File(savePath + file.getOriginalFilename()));  
            }  
        }  
        return "redirect:uploadPage";  
    }
}
